// src-tauri/src/approval_workflow.rs
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};

use crate::content_verification::ContentMetadata;

#[derive(Serialize, Deserialize, Clone)]
pub struct ApprovalRequest {
    pub content_hash: String,
    pub submitter_peer_id: String,
    pub metadata: ContentMetadata,
    pub timestamp: u64,
    pub status: ApprovalStatus,
    pub assigned_reviewers: Vec<String>, // 分配的审核者
}

#[derive(Serialize, Deserialize, Clone)]
pub enum ApprovalStatus {
    Pending,
    UnderReview,
    Approved,
    Rejected,
    NeedsRevision,
}

pub struct ApprovalWorkflow {
    pending_requests: VecDeque<ApprovalRequest>,
    active_reviews: HashMap<String, ApprovalRequest>, // content_hash -> request
    trusted_peers: Vec<String>,
    max_concurrent_reviews: usize,
}

impl ApprovalWorkflow {
    pub fn new() -> Self {
        Self {
            pending_requests: VecDeque::new(),
            active_reviews: HashMap::new(),
            trusted_peers: Vec::new(),
            max_concurrent_reviews: 5,
        }
    }
    
    pub fn submit_for_approval(
        &mut self,
        content_metadata: ContentMetadata,
        submitter_peer_id: String,
    ) -> String {
        // 计算内容哈希 使用crypto的方法
        let content_hash = content_metadata.file_hash.clone(); // 直接使用metadata中的file_hash
        
        let request = ApprovalRequest {
            content_hash: content_hash.clone(),
            submitter_peer_id,
            metadata: content_metadata,
            timestamp: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(),
            status: ApprovalStatus::Pending,
            assigned_reviewers: Vec::new(),
        };
        
        self.pending_requests.push_back(request);
        content_hash
    }
    
    pub fn assign_reviewers(&mut self) {
        while self.active_reviews.len() < self.max_concurrent_reviews {
            if let Some(mut request) = self.pending_requests.pop_front() {
                // 分配审核者（轮询或基于专业领域）
                let reviewers = self.select_reviewers(&request.metadata);
                request.assigned_reviewers = reviewers;
                request.status = ApprovalStatus::UnderReview;
                
                self.active_reviews.insert(request.content_hash.clone(), request);
            } else {
                break;
            }
        }
    }
    
    pub fn process_review_decision(
        &mut self,
        content_hash: String,
        reviewer_peer_id: String,
        approved: bool,
        comments: String,
    ) -> Result<ApprovalStatus, String> {
        // 先检查请求是否存在，但不进行可变借用
        if !self.active_reviews.contains_key(&content_hash) {
            return Err("Review request not found".to_string());
        }
        
        // 验证审核者权限
        let request = self.active_reviews.get(&content_hash).unwrap();
        if !request.assigned_reviewers.contains(&reviewer_peer_id) {
            return Err("Peer not assigned to review this content".to_string());
        }
        
        // 获取请求的可变引用并更新状态
        let request = self.active_reviews.get_mut(&content_hash).unwrap();
        
        // 简单的多数投票机制
        // 在实际系统中可以实现更复杂的投票逻辑
        let status = if approved {
            request.status = ApprovalStatus::Approved;
            
            // 通知信任链记录批准
            // trust_chain.approve_content(...)
            ApprovalStatus::Approved
        } else {
            request.status = ApprovalStatus::Rejected;
            ApprovalStatus::Rejected
        };
        
        // 从活跃审核中移除
        let removed_request = self.active_reviews.remove(&content_hash);
        
        Ok(status)
    }
    
    fn select_reviewers(&self, metadata: &ContentMetadata) -> Vec<String> {
        // 基于内容类型选择专业对口的审核者
        // 简化实现：选择前3个可用的Trusted Peer
        self.trusted_peers.iter()
            .take(3)
            .cloned()
            .collect()
    }
    
    pub fn add_trusted_peer(&mut self, peer_id: String) {
        if !self.trusted_peers.contains(&peer_id) {
            self.trusted_peers.push(peer_id);
        }
    }
}